<template>
  <div class="topbar">
    <div class="wrap topbarWrap">
      <div class="left">欢迎来到叩丁狼积分商城</div>
      <ul class="right">
        <li @click="changeIsShowLoginModel(true)">
          <img :src="userInfo.headImg" alt="" />
          用户名：{{ userInfo.nickName }}
        </li>
        <li @click="changeIsShowLoginModel(true)">
          我的积分：{{ userInfo.coin }}
        </li>
        <li @click="changeIsShowLoginModel(true)">获取积分</li>
        <li>叩丁狼官网</li>
        <li
          class="loginBtn"
          @click="changeIsShowLoginModel(true)"
          v-show="isShowLogined"
        >
          登录
        </li>
        <li class="cart-btn" v-show="!isShowLogined">
          <img src="../assets/img/cart.png" alt="" />
          <span>购物车</span>
          <strong>{{ cartTotal }}</strong>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from "vuex";
import { weiXinLoginApi } from "@/request/Api";
export default {
  data() {
    return {
      //购物车总数
      // cartTotal: 0, // 因为用户数据多个组件都要用，所以把数据放在 vuex 里
    };
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModel: "showLoginModel/changeIsShowLoginModel",
      changeIsShowLogined: "loginStates/changeIsShowLogined",
      initUserInfo: "userInfo/initUserInfo",
    }),
    ...mapActions({
      asyncShowToast: "showToast/asyncShowToast",
      asyncUpdateUserInfo: "userInfo/asyncUpdateUserInfo",
    }),
  },
  computed: {
    ...mapState({
      isShowLogined: (state) => state.loginStates.isShowLogined,
      userInfo: (state) => state.userInfo.userinfo,
      cartTotal: (state) => state.userInfo.cartTotal,
    }),
  },
  // 扫码刷新后，执行 created()
  created() {
    // localStorage.getItem("x-auth-token")
    // console.log("topbar-create", this.$route.query); // 可能created 完时，路由对象还没创建完成，所以获取不到
    this.$router.onReady(async () => {
      // console.log("等路由对象加载完：topbar-create", this.$route.query);
      const pathCode = this.$route.query.code;
      // console.log({ pathCode });

      if (pathCode) {
        // console.log("进来了-----------");
        const weiXinLoginRes = await weiXinLoginApi({ code: pathCode });
        console.log({ weiXinLoginRes });
        if (weiXinLoginRes.code == 0) {
          // 1、提示登录成功
          // alert("扫🐎登录成功！");
          this.asyncShowToast({
            isShow: true,
            msg: "扫🐎登录成功！!",
            type: "success",
          });
          // 2、存token
          localStorage.setItem("x-auth-token", weiXinLoginRes["x-auth-token"]);
          // 3、切换登录按钮
          this.changeIsShowLogined(false);
          // 4、清除地址栏中的code
          this.$router.push("/home");
          // 5、关闭模态框
          this.changeIsShowLoginModel(false);

          // 登录成功后请求更新数据
          this.asyncUpdateUserInfo();
        } else if (weiXinLoginRes.code == 400) {
          // 1、提示二维码失效
          // alert("二维码失效了，请重新登陆");
          this.asyncShowToast({
            isShow: true,
            msg: "二维码失效了，请重新登陆!",
            type: "error",
          });
          // 2、自动打开登录模态框
          this.changeIsShowLoginModel(true);
        } else if (weiXinLoginRes.code == 407) {
          // alert("微信未关联手机号，请用手机号再登录一次！");
          this.asyncShowToast({
            isShow: true,
            msg: "微信未关联手机号，请用手机号再登录一次！!",
            type: "warning",
          });
          this.changeIsShowLoginModel(true);
          localStorage.setItem("uuid", weiXinLoginRes.uuid);
          this.$router.push(this.$route.path);
          // 绑定登录成功后 都是得到 code==0
          // 重现407,去备份地址的个人中心解绑
        }
      } else {
        // 判断登录状态法二：
        // ！！！如果不是微信登录进来的，就会执行这里的代码
        let token = localStorage.getItem("x-auth-token");
        this.changeIsShowLogined(!token);
        if (token) {
          // 已登录重新请求用户信息，解决点击刷新后，已登录的用户信息变回 vuex默认的数据，而不是登录用户的数据
          this.asyncUpdateUserInfo();
        } else {
          // 没登录，过登录状态过期了，就初始化
          this.initUserInfo();
        }
      }
    });
  },

  // 判断登录状态法一：监听路由状态，每次路由路径改变，获取一次登录状态
  /* watch: {
    "$route.path": {
      handler(newVal, oldVal) {
        console.log(newVal, oldVal);
        let token = localStorage.getItem("x-auth-token");
        console.log("x-auth-token:", token);
        this.changeIsShowLogined(!token); // 利用隐式转换为布尔值 效果 !!token == Boolean(!token)
      },
    },
  }, */
  beforeMount() {
    // console.log("beforeMount--topbar-create", this.$route.query);  // 也获取不到
  },
  mounted() {
    // console.log("topbar-create", this.$route.query);  // 都获取不到
  },
};
</script>

<style lang="less" scoped>
.topbar {
  height: 40px;
  background: #242b39;
  color: #fff;
  line-height: 40px;
  min-width: 1200px;
  .topbarWrap {
    display: flex;
    justify-content: space-between;
    .right {
      // width: 510px;
      display: flex;
      justify-content: space-between;
      cursor: pointer;
      li {
        font-size: 14px;
        font-weight: 300;
        margin: 0 10px;
        img {
          width: 26px;
          height: 26px;
          /* background: #7D8696;
          border: 1px solid #8891A1; */
          border-radius: 13px;
          vertical-align: middle;
          margin-bottom: 2px;
        }
        &.loginBtn {
          width: 124px;
          background: #0a328e;
          text-align: center;
        }
        &.cart-btn {
          width: 124px;
          height: 40px;
          background: #0a328e;
          text-align: center;
          img {
            width: 20px;
            height: 19px;
            vertical-align: middle;
          }
          span {
            margin: 0 8px;
          }
          strong {
            width: 22px;
            height: 22px;
            line-height: 22px;
            display: inline-block;
            border-radius: 50%;
            background-color: #fd604d;
          }
        }
      }
    }
  }
}
</style>